<template>
  <div class="employee-data-view">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="view-card">
          <template #header>
            <div class="card-header">
              <span>员工信息多维度数据整合分析</span>
              <!-- <el-button type="primary" @click="showEmployeeDialog = true">
                <el-icon>
                  <Plus />
                </el-icon>
                新增员工
              </el-button> -->
            </div>
          </template>

          <!-- 标签页 -->
          <el-tabs v-model="activeTab" type="card">
            <el-tab-pane label="员工基本信息" name="employees">
              <EmployeeManagement
                :employees="employees"
                @edit-employee="handleEditEmployee"
                @delete-employee="handleDeleteEmployee"
                @view-resume="handleViewResume"
              />
            </el-tab-pane>

            <el-tab-pane label="培训记录管理" name="trainings">
              <TrainingManagement
                :trainings="trainings"
                :employees="employees"
                :name="pxName"
                @add-training="handleAddTraining"
                @edit-training="handleEditTraining"
                @delete-training="handleDeleteTraining"
              />
            </el-tab-pane>

            <el-tab-pane label="绩效数据管理" name="performances">
              <PerformanceManagement
                :performances="performances"
                :employees="employees"
                :name="pxName"
                @add-performance="handleAddPerformance"
                @edit-performance="handleEditPerformance"
                @delete-performance="handleDeletePerformance"
              />
            </el-tab-pane>

            <!-- <el-tab-pane label="岗位要求管理" name="positions">
              <PositionManagement
                :positions="positions"
                @add-position="handleAddPosition"
                @edit-position="handleEditPosition"
                @delete-position="handleDeletePosition"
              />
            </el-tab-pane> -->
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>

    <!-- 员工信息对话框 -->
    <EmployeeDialog
      v-model="showEmployeeDialog"
      :employee="editingEmployee"
      :mode="dialogMode"
      @save="handleSaveEmployee"
      @close="handleCloseDialog"
    />

    <!-- 培训记录对话框 -->
    <TrainingDialog
      v-model="showTrainingDialog"
      :training="editingTraining"
      :employees="employees"
      :mode="trainingDialogMode"
      @save="handleSaveTraining"
      @close="handleCloseTrainingDialog"
    />

    <!-- 绩效数据对话框 -->
    <PerformanceDialog
      v-model="showPerformanceDialog"
      :performance="editingPerformance"
      :employees="employees"
      :mode="performanceDialogMode"
      @save="handleSavePerformance"
      @close="handleClosePerformanceDialog"
    />

    <!-- 岗位要求对话框 -->
    <PositionDialog
      v-model="showPositionDialog"
      :position="editingPosition"
      :mode="positionDialogMode"
      @save="handleSavePosition"
      @close="handleClosePositionDialog"
    />

    <!-- 简历预览对话框 -->
    <EmployeeResume v-model="showResumeDialog" :employee="viewingEmployee" />
  </div>
</template>

<script>
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { useStore } from "vuex";
import { useRoute } from "vue-router";

import EmployeeManagement from "@/components/EmployeeManagement.vue";
import TrainingManagement from "@/components/TrainingManagement.vue";
import PerformanceManagement from "@/components/PerformanceManagement.vue";
import PositionManagement from "@/components/PositionManagement.vue";
import EmployeeDialog from "@/components/EmployeeDialog.vue";
import TrainingDialog from "@/components/TrainingDialog.vue";
import PerformanceDialog from "@/components/PerformanceDialog.vue";
import PositionDialog from "@/components/PositionDialog.vue";
import EmployeeResume from "@/components/EmployeeResume.vue";
import api from "@/services/api";

export default {
  name: "EmployeeDataView",
  components: {
    Plus,
    EmployeeManagement,
    TrainingManagement,
    PerformanceManagement,
    PositionManagement,
    EmployeeDialog,
    TrainingDialog,
    PerformanceDialog,
    PositionDialog,
    EmployeeResume,
  },
  setup() {
    const store = useStore();

    const activeTab = ref("employees");
    const showEmployeeDialog = ref(false);
    const showTrainingDialog = ref(false);
    const showPerformanceDialog = ref(false);
    const showPositionDialog = ref(false);
    const showResumeDialog = ref(false);

    const dialogMode = ref("create");
    const trainingDialogMode = ref("create");
    const performanceDialogMode = ref("create");
    const positionDialogMode = ref("create");

    const editingEmployee = ref(null);
    const editingTraining = ref(null);
    const editingPerformance = ref(null);
    const editingPosition = ref(null);
    const viewingEmployee = ref(null);

    const employees = ref([]);
    const trainings = ref([]);
    const performances = ref([]);
    const positions = ref([]);
    const route = useRoute();
    const pxName = ref("");

    console.log("query 参数：", route.query);
    if (route.query.name) {
      activeTab.value =
        route.query.type == "px"
          ? "trainings"
          : route.query.type == "jx"
          ? "performances"
          : "employees";
      pxName.value = route.query.name;
    }

    const loadData = async () => {
      try {
        const resEmployees = await api.getEmployees();
        employees.value = resEmployees.data;
      } catch (error) {
        console.error("加载员工数据失败:", error);
      }
      try {
        const resTrainings = await api.getTrainings();
        trainings.value = resTrainings.data;
      } catch (error) {
        console.error("加载培训数据失败:", error);
      }

      try {
        const resPerformances = await api.getPerformances();
        performances.value = resPerformances.data;
      } catch (error) {
        console.error("加载绩效数据失败:", error);
      }
      try {
        const resPositions = await api.getPositions();
        positions.value = resPositions.data;
      } catch (error) {
        console.error("加载岗位数据失败:", error);
      }
    };

    // 员工相关操作
    const handleEditEmployee = (employee) => {
      editingEmployee.value = { ...employee };
      dialogMode.value = "edit";
      showEmployeeDialog.value = true;
    };

    const handleDeleteEmployee = async (employee) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除员工"${employee.name}"吗？此操作不可恢复。`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        await api.deleteEmployee(employee.id);
        store.commit("DELETE_EMPLOYEE", employee.id);
        ElMessage.success("员工删除成功");
        let resEmployees = await api.getEmployees();
        employees.value = resEmployees.data;
      } catch (error) {
        if (error !== "cancel") {
          ElMessage.error("删除失败");
        }
      }
    };

    const handleViewResume = (employee) => {
      viewingEmployee.value = employee;
      showResumeDialog.value = true;
    };

    const handleSaveEmployee = async (employeeData) => {
      try {
        let savedEmployee;
        if (dialogMode.value === "create") {
          savedEmployee = await api.createEmployee(employeeData);
          store.commit("ADD_EMPLOYEE", savedEmployee.data);
        } else {
          savedEmployee = await api.updateEmployee(
            employeeData.id,
            employeeData
          );
          store.commit("UPDATE_EMPLOYEE", savedEmployee.data);
        }

        showEmployeeDialog.value = false;
        let resEmployees = await api.getEmployees();
        employees.value = resEmployees.data;
        ElMessage.success(
          `员工${dialogMode.value === "create" ? "创建" : "更新"}成功`
        );
      } catch (error) {
        ElMessage.error(
          `员工${dialogMode.value === "create" ? "创建" : "更新"}失败`
        );
      }
    };

    const handleCloseDialog = () => {
      editingEmployee.value = null;
      showEmployeeDialog.value = false;
    };

    // 培训记录相关操作
    const handleEditTraining = (training) => {
      editingTraining.value = { ...training };
      trainingDialogMode.value = "edit";
      showTrainingDialog.value = true;
    };

    const handleDeleteTraining = async (training) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除"${training.courseName}"培训记录吗？`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        await api.deleteTraining(training.id);
        await loadData(); // 重新加载数据
        ElMessage.success("培训记录删除成功");
      } catch (error) {
        if (error !== "cancel") {
          ElMessage.error("删除失败");
        }
      }
    };

    const handleSaveTraining = async (trainingData) => {
      try {
        if (trainingDialogMode.value === "create") {
          await api.createTraining(trainingData);
        } else {
          await api.updateTraining(trainingData.id, trainingData);
        }

        showTrainingDialog.value = false;
        await loadData(); // 重新加载数据
        ElMessage.success(
          `培训记录${
            trainingDialogMode.value === "create" ? "创建" : "更新"
          }成功`
        );
      } catch (error) {
        ElMessage.error(
          `培训记录${
            trainingDialogMode.value === "create" ? "创建" : "更新"
          }失败`
        );
      }
    };

    const handleCloseTrainingDialog = () => {
      editingTraining.value = null;
      showTrainingDialog.value = false;
    };

    // 绩效数据相关操作
    const handleEditPerformance = (performance) => {
      editingPerformance.value = { ...performance };
      performanceDialogMode.value = "edit";
      showPerformanceDialog.value = true;
    };

    const handleDeletePerformance = async (performance) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除${performance.period}的绩效记录吗？`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        await api.deletePerformance(performance.id);
        await loadData(); // 重新加载数据
        ElMessage.success("绩效记录删除成功");
      } catch (error) {
        if (error !== "cancel") {
          ElMessage.error("删除失败");
        }
      }
    };

    const handleSavePerformance = async (performanceData) => {
      try {
        if (performanceDialogMode.value === "create") {
          await api.createPerformance(performanceData);
        } else {
          await api.updatePerformance(performanceData.id, performanceData);
        }

        showPerformanceDialog.value = false;
        await loadData(); // 重新加载数据
        ElMessage.success(
          `绩效记录${
            performanceDialogMode.value === "create" ? "创建" : "更新"
          }成功`
        );
      } catch (error) {
        ElMessage.error(
          `绩效记录${
            performanceDialogMode.value === "create" ? "创建" : "更新"
          }失败`
        );
      }
    };

    const handleClosePerformanceDialog = () => {
      editingPerformance.value = null;
      showPerformanceDialog.value = false;
    };

    // 岗位要求相关操作
    const handleEditPosition = (position) => {
      editingPosition.value = { ...position };
      positionDialogMode.value = "edit";
      showPositionDialog.value = true;
    };

    const handleDeletePosition = async (position) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除"${position.positionName}"岗位要求吗？`,
          "确认删除",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        );

        await api.deletePosition(position.id);
        await loadData(); // 重新加载数据
        ElMessage.success("岗位要求删除成功");
      } catch (error) {
        if (error !== "cancel") {
          ElMessage.error("删除失败");
        }
      }
    };

    const handleSavePosition = async (positionData) => {
      try {
        if (positionDialogMode.value === "create") {
          await api.createPosition(positionData);
        } else {
          await api.updatePosition(positionData.id, positionData);
        }

        showPositionDialog.value = false;
        await loadData(); // 重新加载数据
        ElMessage.success(
          `岗位要求${
            positionDialogMode.value === "create" ? "创建" : "更新"
          }成功`
        );
      } catch (error) {
        ElMessage.error(
          `岗位要求${
            positionDialogMode.value === "create" ? "创建" : "更新"
          }失败`
        );
      }
    };

    const handleClosePositionDialog = () => {
      editingPosition.value = null;
      showPositionDialog.value = false;
    };

    // 添加培训记录
    const handleAddTraining = () => {
      editingTraining.value = null;
      trainingDialogMode.value = "create";
      showTrainingDialog.value = true;
    };

    // 添加绩效记录
    const handleAddPerformance = () => {
      editingPerformance.value = null;
      performanceDialogMode.value = "create";
      showPerformanceDialog.value = true;
    };

    // 添加岗位要求
    const handleAddPosition = () => {
      editingPosition.value = null;
      positionDialogMode.value = "create";
      showPositionDialog.value = true;
    };

    onMounted(() => {
      loadData();
    });

    return {
      activeTab,
      showEmployeeDialog,
      showTrainingDialog,
      showPerformanceDialog,
      showPositionDialog,
      showResumeDialog,
      dialogMode,
      trainingDialogMode,
      performanceDialogMode,
      positionDialogMode,
      editingEmployee,
      editingTraining,
      editingPerformance,
      editingPosition,
      viewingEmployee,
      employees,
      trainings,
      performances,
      positions,
      handleEditEmployee,
      handleDeleteEmployee,
      handleViewResume,
      handleSaveEmployee,
      handleCloseDialog,
      handleEditTraining,
      handleDeleteTraining,
      handleSaveTraining,
      handleCloseTrainingDialog,
      handleEditPerformance,
      handleDeletePerformance,
      handleSavePerformance,
      handleClosePerformanceDialog,
      handleEditPosition,
      handleDeletePosition,
      handleSavePosition,
      handleClosePositionDialog,
      handleAddPosition,
      handleAddPerformance,
      handleAddTraining,
      pxName,
    };
  },
};
</script>

<style scoped>
.employee-data-view {
  height: 100%;
}

.view-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-tabs__content) {
  padding: 20px 0;
}
</style>
